//
//  RequestManager+GR.m
//  YCGRICE
//
//  Created by Liu Feng on 2018/7/5.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "RequestManager+GR.h"
#import "NSMutableURLRequest+GR.h"

NSString * const erMsg  = @"errorMessage";
NSString * const ptMsg  = @"promptMessage";
NSString * const ercode = @"errorCode";

@implementation RequestManager (GR)

+ (void)dataTasKWithRequest:(NSMutableURLRequest *)request completionHandler:(RequestBlock  )completionHandler {
    [request setValue:APPVERSON forHTTPHeaderField:@"iosApi"];
    [request setValue:@"gm" forHTTPHeaderField:@"app"];
    [request setValue:@"application/json;text/json;text/javascript;image/jpeg" forHTTPHeaderField:@"Accept"];
    
    NSURLSessionDataTask *dataTask = [[AFHTTPSessionManager manager] dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%@",uploadProgress);
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%@",downloadProgress);
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Http = %@\n Paramers = %@\n Request_Fail：%@\n",response.URL, request.paramers, error);
            [self dataProcessWithError:error completionHandler:completionHandler];
        }else {
            NSLog(@"Http = %@\n Paramers = %@\n Request_Success：%@\n",response.URL, request.paramers, responseObject);
            [self dataProcessWithResponseObject:responseObject completionHandler:completionHandler];
        }
    }];
    
    [dataTask resume];
}



+(void)uploadWithStreamedRequest:(NSMutableURLRequest*)request progress:(void (^)(NSProgress *uploadProgress))progressBlock completionHandler:(RequestBlock)completionHandler {
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    AFHTTPResponseSerializer *serializer = [AFHTTPResponseSerializer serializer];
    [serializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/plain", nil]];
    sessionManager.responseSerializer = serializer;
    
    NSURLSessionUploadTask *uploadTask = [sessionManager uploadTaskWithStreamedRequest:request progress:progressBlock completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Http = %@\n Paramers = %@\n Request_Fail：%@\n",response.URL, request.paramers, error);
            [self dataProcessWithError:error completionHandler:completionHandler];
        }else {
            NSLog(@"Http = %@\n Paramers = %@\n Request_Success：%@\n",response.URL, request.paramers, responseObject);
            [self dataProcessWithResponseObject:responseObject completionHandler:completionHandler];
        }
    }];
    [uploadTask resume];
}




/**
 请求成功的数据处理

 @param responseObject <#responseObject description#>
 @param completionHandler <#completionHandler description#>
 */
+ (void)dataProcessWithResponseObject:(id)responseObject completionHandler:(RequestBlock)completionHandler {
    NSDictionary *response = responseObject;
    
    if (response && [response isKindOfClass:[NSDictionary class]]) {
        BOOL success = [responseObject[@"succeeded"] boolValue];
        id data    = responseObject[@"data"];
        id error   = responseObject[@"error"];
        id message = responseObject[@"message"];

        if (success && (data || message)) {
// 成功处理
            if (completionHandler) {
                if (data) {
                    completionHandler(YES, data, nil);
                }else {
                    completionHandler(YES, message, nil);
                }
            }
            
        }else {
// 失败处理
            if (error) {
                NSString *code       = error[@"code"];
                NSString *errordespt = error[@"descript"];
                NSString *msgdespt   = message[@"descript"];
                
                NSDictionary *option    = @{erMsg : NSStringNotNULL(errordespt) ? errordespt : @"",
                                            ptMsg : NSStringNotNULL(msgdespt) ? msgdespt : @"",
                                            ercode: code
                                            };
                GRError *grError = [[GRError alloc] initWithErrorCode:0 userInfo:option];
                if (completionHandler) {
                    completionHandler(NO, nil, grError);
                }
            }
            
        }
        
    }
}



/**
 请求失败的数据处理

 @param error <#error description#>
 @param completionHandler <#completionHandler description#>
 */
+ (void)dataProcessWithError:(NSError *)error completionHandler:(RequestBlock)completionHandler {
    GRError *gr_error = [GRError errorWithDomain:error.domain code:error.code userInfo:error.userInfo];
    completionHandler(NO, nil, gr_error);
}



@end
